//
//  BoZeDataHelper.swift
//  BoZeCalendar
//
//  Created by 李东 on 2024/4/11.
//

import UIKit

class BoZeDataHelper: NSObject {
    static let shared = BoZeDataHelper()
    let LocalKey = "mydataKey"
    lazy var array = [BoZeCarModel]()
    

    
    func getLocalList() -> [BoZeCarModel] {
//        if !array.isEmpty {
//            return array
//        }
        if let tt = UserDefaults.standard.object(forKey: LocalKey) as? String {
            if let list = [BoZeCarModel].deserialize(from: tt) as? [BoZeCarModel] {
                array = list.sorted(by: { m1, m2 in
                    m1.ids > m2.ids
                })
            }
        }
        return array
    }
    
    func addData(model: BoZeCarModel)  {
        if array.contains(where: {$0.carName == model.carName}) {
            if let ii = array.firstIndex(where: {$0.carName == model.carName}) {
                array[ii] = model
            }
        }else {
//            array.append(model)
            array.insert(model, at: 0)
        }
        if let json = array.toJSONString() {
            UserDefaults.standard.set(json, forKey: LocalKey)
            UserDefaults.standard.synchronize()
        }
    }
}
